﻿angular.module("taskRecordApp")
.directive("taskRecordAdd", ["requestService", "editConditionService", "bindCorrectOptionService", function (requestService, editConditionService, bindCorrectOptionService) {
    return {
        restrict: "E",
        templateUrl: "Views/Home/TaskRecordDirective/TaskRecordAddTemplate.html",
        scope: {
            taskRecordsResource: "=",
            taskRecords: "=",
            newTaskRecord: "=",
            saving: "=",
            canEdit: "="
        },
        link: function (scope, elment, attrs, ctrl) {
            scope.editing = function(task,input) {
                if (scope.canEdit) {
                    task[input] = true;
                }
            };

            scope.addNewTaskRecord = function () {
                var resources = scope.taskRecordsResource.apiLinks;

                if (!scope.newTaskRecord.content || !scope.canEdit) {
                    return;
                }
                scope.saving = true;
                requestService.postRequest(scope.newTaskRecord, resources.addTaskRecord)
                    .then(function (data) {
                        scope.taskRecordsResource = data;
                        bindCorrectOptionService.bind(scope.taskRecordsResource);
                        scope.saving = false;
                    });
            }

            scope.updateTaskRecord = function (taskRecord) {
                var resources = scope.taskRecordsResource.apiLinks;

                if (!taskRecord.content || !editConditionService.canEdit(scope.taskRecordsResource.queryDate)) {
                    return;
                }
                scope.saving = true;
                requestService.postRequest(taskRecord, resources.updateTaskRecord)
                    .then(function (data) {
                        scope.taskRecordsResource = data;
                        bindCorrectOptionService.bind(scope.taskRecordsResource);
                        scope.saving = false;
                    });
            }
        }
    }
}]);